<template>
  <div v-if="editAuth">
    <page-header
      :title="$route.query.id ? $t('m.branch_Edit') : $t('m.branch_Create')"
      is-emphasize
    >
      <el-button @click="saveClick('params')" v-if="getAgentLevel() != 2">{{
        $route.query.id ? $t('m.save') : $t('m.branch_Create')
      }}</el-button>
    </page-header>
    <div class="detail_div container">
      <div class="detail_left">
        <div class="detail_left_div" style="padding-bottom: 20px">
          <el-form
            label-position="top"
            :model="params"
            :rules="paramsRule"
            ref="params"
          >
            <div class="create_title">{{ $t('m.Franchisee_information') }}</div>
            <div class="create_title2">
              {{ $t('m.Shop_Details_Franchisee') }}*
            </div>
            <el-form-item prop="agentName">
              <el-input
                v-model="params.agentName"
                :placeholder="$t('m.Please_enter')"
                maxlength="50"
                clearable
              ></el-input>
            </el-form-item>
            <div class="create_title2">
              {{ $t('m.Shop_Details_Profit_allocation') }}（%）*
            </div>
            <el-form-item prop="ratio">
              <el-input
                v-model="params.ratio"
                :placeholder="$t('m.Please_enter')"
                @input="changeRatio"
                maxlength="3"
                clearable
                ><template slot="append">%</template></el-input
              >
            </el-form-item>
            <el-form-item :label="$t('m.branch_Address')">
              <el-input
                v-model="params.address"
                maxlength="100"
                :placeholder="$t('m.Please_enter')"
                clearable
              ></el-input>
            </el-form-item>
            <el-form-item :label="$t('m.Agency_Details_Region')">
              <el-input
                v-model="params.areaAddress"
                maxlength="100"
                :placeholder="$t('m.Please_enter')"
                clearable
              ></el-input>
            </el-form-item>
            <div class="create_title">{{ $t('m.Person_inCharge') }}</div>
            <div class="create_title2">{{ $t('m.Person_In_charge') }}*</div>
            <el-form-item prop="principal">
              <el-input
                v-model="params.principal"
                :placeholder="$t('m.Please_enter')"
                maxlength="20"
                clearable
              ></el-input>
            </el-form-item>
            <div class="create_title2">{{ $t('m.Shop_Details_Contact') }}*</div>
            <el-form-item prop="phone">
              <div class="flex_div">
                <el-select
                  v-model="params.code"
                  :placeholder="$t('m.pleaseChoose')"
                  style="width: 120px; margin-right: 12px"
                  filterable
                >
                  <el-option
                    v-for="(item, index) in countryCode"
                    :key="index"
                    :label="'+' + item.codes"
                    :value="Number(item.codes)"
                  >
                  </el-option>
                </el-select>
                <el-input
                  clearable
                  v-model="params.phone"
                  :placeholder="$t('m.Please_enter')"
                  @input="changePhone"
                  maxlength="15"
                  minlength="8"
                />
              </div>
            </el-form-item>
            <div class="create_title2" v-if="!params.id">
              {{ $t('m.Franchisee_main_account') }}*
            </div>
            <el-form-item prop="accountPhone" v-if="!params.id">
              <div class="flex_div">
                <el-select
                  v-model="params.accountCode"
                  :placeholder="$t('m.pleaseChoose')"
                  style="width: 120px; margin-right: 12px"
                  filterable
                >
                  <el-option
                    v-for="(item, index) in countryCode"
                    :key="index"
                    :label="'+' + item.codes"
                    :value="Number(item.codes)"
                  >
                  </el-option>
                </el-select>
                <el-input
                  clearable
                  v-model="params.accountPhone"
                  :placeholder="$t('m.Please_enter')"
                  @input="changeAccountPhone"
                  maxlength="15"
                  minlength="8"
                />
              </div>
            </el-form-item>
            <div class="create_title2" v-if="!params.id">
              {{ $t('m.Password') }}*
            </div>
            <el-form-item prop="password" v-if="!params.id">
              <el-input
                v-model="params.password"
                @input="changePassword"
                :placeholder="$t('m.Please_enter')"
                clearable
                minlength="8"
                maxlength="16"
              >
                <template slot="append"
                  ><div
                    @click="generatePassword('params')"
                    style="background: #ffffff"
                  >
                    {{ $t('m.Account_Created_Auto_generate') }}
                  </div>
                </template>
              </el-input>
            </el-form-item>
          </el-form>
        </div>
      </div>
      <div class="detail_right">
        <div class="detail_left_div" style="padding-bottom: 20px">
          <div class="create_title">
            {{ $t('m.branch_branch_Assign_station') }}
          </div>
          <el-transfer
            filterable
            :filter-placeholder="$t('m.Station_SN')"
            v-model="params.scanList"
            :titles="[$t('m.Station_list'), $t('m.Station_assigned')]"
            :data="stations"
            :render-content="renderContent"
          >
          </el-transfer>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import countries from '@/common/json/countries.json'
export default {
  data() {
    // 验证密码
    const checkPassword = (rule, value, callback) => {
      let reg = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9a-zA-Z]{8,16}$/
      if (!value) {
        return callback(new Error(this.$t('m.Enterpassword')))
      } else if (!reg.test(value)) {
        return callback(new Error(this.$t('m.Set_login_password')))
      } else {
        callback()
      }
    }
    return {
      params: {
        address: '', //	地址
        areaAddress: '', //	代理区域
        agentName: '', //	代理商名称
        code: this.$country.codes, //	国家码
        accountCode: this.$country.codes, //	国家码
        id: '', //	主键id
        parentAgentId: '', //上级代理id（默认为0则没有上级代理）
        password: '', //密码
        phone: '', //	联系电话
        accountPhone: '', //	管理员电话
        principal: '', //	负责人
        ratio: '', //	分成比例：1-90
        scanList: [], //选中机柜
        logo: '',
      },
      paramsRule: {
        agentName: [
          {
            required: true,
            message: this.$t('m.Shop_Created_franchisee'),
            trigger: 'blur',
          },
        ],
        phone: [
          {
            required: true,
            trigger: 'blur',
            message: this.$t('m.Enterphonenumber2'),
          },
        ],
        accountPhone: [
          {
            required: true,
            trigger: 'blur',
            message: this.$t('m.Please_enter_franchisee_main_account'),
          },
        ],
        password: [
          { required: true, trigger: 'blur', validator: checkPassword },
        ],
        ratio: [
          {
            required: true,
            trigger: 'blur',
            message: this.$t('m.Shop_Created_shop_profit_allocation'),
          },
        ],
        principal: [
          {
            required: true,
            trigger: 'blur',
            message: this.$t('m.Enter_principal'),
          },
        ],
      },
      countryCode: '', //国家码
      stations: [], // 机柜
      editStations: [], //回显机柜
      editAuth: this.permissionsId(27), //代理商编辑
    }
  },
  created() {
    if (!this.editAuth) {
      return
    }
    this.countryCode = countries
    if (this.$route.query.id) {
      this.getDetails()
    } else {
      this.getCabinets()
    }
  },
  mounted() {},
  methods: {
    renderContent(h, option) {
      return (
        <span>
          <span
            class="label"
            style="font-size: 12px !important;line-height: 14px !important;"
          >
            {option.label}
            <span style="padding:0 2px;">·</span>
            {option.deviceCount}
            {this.$t('m.Station_List_placeholder_Device_info')}
          </span>
          <br />
          <span
            class="name"
            style="font-size: 12px !important;line-height: 14px !important; color:#888888;"
          >
            {option.isScreen == 0
              ? this.$t('m.Without_screen')
              : this.$t('m.Advertising_screen')}
          </span>
        </span>
      )
    },
    //获取代理回显
    getDetails() {
      this.$api.agent.agentDetails(this.$route.query.id).then(res => {
        if (this.$ok(res)) {
          this.params = {
            address: res.data.address, //	地址
            areaAddress: res.data.areaAddress, //	代理区域
            agentName: res.data.agentName, //	代理商名称
            code: res.data.code, //	国家码
            id: res.data.id, //	主键id
            parentAgentId: res.data.parentAgentId, //上级代理id（默认为0则没有上级代理）
            phone: res.data.phone, //	电话
            principal: res.data.principal, //	负责人
            ratio: res.data.ratio, //	分成比例：1-90
            scanList: [], //选中机柜
            logo: res.data.logo,
          }
          this.editStations = res.data.list
          this.getCabinets()
        }
      })
    },
    //手机号输入限制
    changePhone(val) {
      this.params.phone = this.$check.onlyNum(val)
    },
    //手机号输入限制
    changeAccountPhone(val) {
      this.params.accountPhone = this.$check.onlyNum(val)
    },
    //分成比例输入限制
    changeRatio(val) {
      this.params.ratio = this.$check.onlyNum(val)
      if (this.params.ratio > 100) {
        this.params.ratio = 100
      }
    },
    //密码输入限制
    changePassword(val) {
      this.params.password = this.$check.password(val)
    },
    //获取机柜
    getCabinets() {
      let params = {
        type: 1,
        // agentId: this.$route.query.id ? this.$route.query.id : ''
      }
      this.$api.shop.getCabinetsList(params).then(res => {
        if (this.$ok(res)) {
          res.data.forEach(item => {
            this.stations.push({
              label: item.cabinetNo,
              key: item.cabinetNo,
              deviceCount: item.deviceCount,
              isScreen: item.isScreen,
            })
          })
          this.editStations.forEach(item => {
            this.stations.push({
              label: item.cabinetNo,
              key: item.cabinetNo,
              deviceCount: item.deviceCount,
              isScreen: item.isScreen,
            })
            this.params.scanList.push(item.cabinetNo)
          })
        }
      })
    },
    //保存/编辑
    saveClick(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          if (this.$route.query.id) {
            this.$api.agent.editAgent(this.params).then(res => {
              if (this.$ok(res)) {
                this.$message.success(res.message)
                this.$router.go(-1)
              } else {
                this.$message.error(res.message)
              }
            })
          } else {
            const params = { ...this.params }
            params.password = this.$md5(this.params.password)
            this.$api.agent.addAgent(params).then(res => {
              if (this.$ok(res)) {
                this.$message.success(res.message)
                this.remPageNum()
                this.$router.go(-1)
              } else {
                this.$message.error(res.message)
              }
            })
          }
        } else {
          // console.log('error submit!!')
          return false
        }
      })
    },
    //随机生成密码
    generatePassword(formName) {
      this.randomGeneration(8)
      if (this.params.password) {
        this.$refs[formName].validateField('password')
      }
    },
    // 生成随机数字和字母的组合
    randomGeneration(length) {
      let reg = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]/
      let result = ''
      const characters =
        'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
      const charactersLength = characters.length
      for (let i = 0; i < length; i++) {
        result += characters.charAt(
          Math.floor(Math.random() * charactersLength)
        )
      }
      if (!reg.test(result)) {
        this.randomGeneration(length)
      } else {
        this.params.password = result
      }
    },
  },
}
</script>
<style>
.el_tooltip_hit {
  max-width: 500px !important;
}
</style>
<style lang="scss" scoped>
.page-header,
.container {
  min-width: 1360px !important;
}

.hitImg {
  width: 16px;
  height: 16px;
  cursor: pointer;
  margin-left: 6px;
}
.agent_logo {
  width: 85px;
  height: 115px;
  position: relative;
  .upload_img {
    position: absolute;
    width: 75px !important;
    height: 75px !important;
    border-radius: 50%;
    top: 5px;
    left: 5px;
  }
}
.preview_btn {
  width: 85px;
  font-size: 12px;
  font-weight: 600;
  text-align: center;
  color: #39404d;
  line-height: 17px;
  cursor: pointer;
  margin-top: 12px;
}
.el_button_logo {
  margin: 20px 0;
  height: 36px !important;
}
</style>
./comps/cropper-marker-image.vue
